﻿using System.ComponentModel;

namespace Microsoft.Extensions;

/// <summary>
/// 枚举相关扩展
/// </summary>
public static class EnumExtensions
{
    /// <summary>
    ///     获取枚举项上的<see cref="DescriptionAttribute" />特性的文字描述
    /// </summary>
    /// <param name="enum"></param>
    /// <returns></returns>
    public static string GetDescription(this Enum @enum)
    {
        var enumType = @enum.GetType();
        // 获取枚举常数名称。
        var name = Enum.GetName(enumType, @enum);
        if (name != null)
        {
            // 获取枚举字段。
            var fieldInfo = enumType.GetField(name);
            if (fieldInfo != null)
                // 获取描述的属性。
                if (Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute), false) is DescriptionAttribute attr)
                    return attr.Description;
        }
        return null;
    }

    /// <summary>
    /// 获取int值
    /// </summary>
    /// <param name="enum"></param>
    /// <returns></returns>
    public static int ConvertToInt(this Enum @enum)
    {
        return Convert.ToInt32(@enum);
    }

    /// <summary>
    /// 获取枚举值并转换成string
    /// </summary>
    /// <param name="enum"></param>
    /// <returns></returns>
    public static string ToStringValue(this Enum @enum)
    {
        return Convert.ToInt32(@enum).ToString();
    }
}
